package com.iclient.dao.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iclient.dao.mapper.ImgMapper;
import com.iclient.dao.mapper.MCookieMapper;
import com.iclient.dao.model.Img;
import com.iclient.dao.model.MCookie;
import com.iclient.dao.service.ImgService;

@Service("imgService")
public class ImgServiceImpl implements ImgService{

	@Autowired
	private ImgMapper imgMapper;
	@Autowired
	private MCookieMapper cookieMapper;
	
	@Override
	public void delete(String type){
		imgMapper.deleteBy(type);
	}
	
	@Override
	public void insert(Img img) {
		imgMapper.deleteBy(img.getImgType());
		imgMapper.insert(img);
	}

	@Override
	public Img findImg(String type) {
		return imgMapper.selectBy(type);
	}

	@Override
	public void update(Img img) {
		imgMapper.updateBy(img);
	}

	@Override
	public String getCode() {
		String code = "";
		int retry = 0;
		try{
			while(StringUtils.isBlank(code)){
				retry += 1;
				if(retry >= 36)
					break;
				Img img = findImg("msinalogin");
				if(null != img)
					code = img.getCode();
				System.out.println("getCode: \t" + code);
				Thread.sleep(5000);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return code;
	}
	
	public void addCookie(String cookieText){
		MCookie mcookie = new MCookie();
		mcookie.setContent(cookieText);
		cookieMapper.insert(mcookie);
	}

}
